package com.hl.controller.Chat;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hl.domain.ChatMessage;
import com.hl.domain.R;
import com.hl.service.ChatMessageService;
import com.hl.Conf.SpringContextHolder;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import java.io.IOException;

import static com.fasterxml.jackson.databind.type.LogicalType.Map;
import static com.hl.domain.WebSocketUtils.sendMessage;
import static com.hl.domain.WebSocketUtils.user_session;

@RestController
@ServerEndpoint("/chat/{userName}")
public class ChatService {
    private static final Logger logger = LoggerFactory.getLogger(ChatService.class);

    // 建立连接
    @OnOpen
    public void onOpen(@PathParam("userName") String userName, Session session) {

        user_session.put(userName, session);
        //先记录是谁建立的连接
        session.getUserProperties().put("userName", userName);
//        logger.debug("WebSocket连接建立: {}", userName);
    }

    // 接收消息：用户发来的消息统一转发给客服 "kefu"
    @OnMessage
    public void onMessage( String  touser, Session Session) {
//        logger.debug("收到消息, from={}, msg={}", userName, message);
        ObjectMapper mapper = new ObjectMapper();
        //得到建立连接的用户名
        String username=  (String) Session.getUserProperties().get("userName");
        ChatMessage chatMessage = null;
        String content;
        String to;
        try {
            //将前端返回的json反序列化，解析出发给谁，发什么内容
            chatMessage = new ObjectMapper().readValue(touser, ChatMessage.class);
            ChatMessageService svc = SpringContextHolder.getBean(ChatMessageService.class);
            if ("kefu".equals(username)) {
                // 客服 -> 指定用户
                svc.saveIncoming(null, username, chatMessage.getTo(), chatMessage.getContent(), 1);
                sendMessage(chatMessage.getTo(), chatMessage.getContent());
            } else {
                // 用户 -> 客服，带上来源
                ObjectNode node = mapper.createObjectNode();
                node.put("from", username);
                node.put("content", chatMessage.getContent());
                svc.saveIncoming(null, username, "kefu", chatMessage.getContent(), 1);
                sendMessage("kefu", mapper.writeValueAsString(node));
            }
        } catch (JsonProcessingException e) {
            //如果解析失败，说明是用户发送的消息，直接转发给客服
            ChatMessageService svc = SpringContextHolder.getBean(ChatMessageService.class);
            svc.saveIncoming(null, username, "kefu", touser, 1);
            String toKefu = "{\"from\":\"" + username + "\",\"content\":" + new ObjectMapper().valueToTree(touser).toString() + "}";
            sendMessage("kefu", toKefu);
        }
//        if (to != null && content != null) {
//            sendMessage(to, content);
//        }
    }

    // 关闭连接
    @OnClose
    public void onClose(Session session) {
        String userName = (String) session.getUserProperties().get("userName");
        user_session.remove(userName);
        Session kefu = user_session.get("kefu");
        if (kefu != null && kefu.isOpen() && !"kefu".equals(userName)) {
            sendMessage("kefu", userName + "已离开会话");
        }
    }

    // 异常处理
    @OnError
    public void onError(Session session, Throwable error) {
//        logger.error("WebSocket异常", error);
        try {
            session.close();
        } catch (IOException e) {
//            logger.error("异常后关闭会话失败", e);
        }
    }
}
